﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dycox
{
    public class CollectionInfo
    {
        private CollectionInfo()
        {
            
        }

        private bool _isCollection;

        public bool IsCollection
        {
            get { return _isCollection; }
        }


        private Type _elementType;

        public Type ElementType
        {
            get { return _elementType; }
        }

        public bool IsGeneric
        {
            get { return _elementType != null; }
        }

        public static bool TryCreate(Type type, out CollectionInfo info)
        {
            Type it;

            it = type.GetInterface("ICollection`1");
            if (it != null)
            {
                if (it.GetGenericTypeDefinition() == typeof(ICollection<>))
                {
                    info = new CollectionInfo();
                    info._elementType = it.GetGenericArguments()[0];
                    info._isCollection = true;
                    return true;
                }
            }

            it = type.GetInterface("ICollection");
            if (it == typeof(ICollection))
            {
                info = new CollectionInfo();
                info._isCollection = true;
                return true;
            }

            it = type.GetInterface("IEnumerable`1");
            if (it != null)
            {
                if (it.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                {
                    info = new CollectionInfo();
                    info._elementType = it.GetGenericArguments()[0];
                    return true;
                }
            }

            it = type.GetInterface("IEnumerable");
            if (it == typeof(IEnumerable))
            {
                info = new CollectionInfo();
                return true;
            }

            info = null;
            return false;
        }
    }
}
